// pages/songPackage/pages/mvplay/mvplay.js
import request from '../../../../utils/request'
// 获取全局实例
const appInstance = getApp();
const DB = wx.cloud.database();
const collectDB = DB.collection("collect")
const _ = DB.command
Page({

    /**
     * 页面的初始数据
     */
    data: {
        src: '',
        danmuList: [
          // {
          //   text: '第 1s 出现的弹幕',
          //   color: '#cccccc',
          //   time: 1
          // },
        ],
        commentTab:['推荐',"评论"],
        mvid:0,
        inputValue: '',     //弹幕信息
        mvurl:'',
        mvDetail:[],         //mv作者  
        mvInfo:[],             //mv信息  
        mvComment:[],           //评论
        duration:0,            //播放时长
        TabCur:0,        //评论简介切换
        enableDanmu:'',
        simiMvs:[],       //相似mv
        shoucang:false
       
    },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      let id = options.vid
      let enableDanmu=''
      let stoenableDanmu = wx.getStorageSync('enableDanmu').toString()
      if(stoenableDanmu){
         enableDanmu = wx.getStorageSync('enableDanmu')
      }else{
        
         enableDanmu = true
      }
      
      this.setData({
        enableDanmu,
        mvid:id
      })
       
       //获取音乐url
       this.getmvUrl(id)
    },

    shoucang(){
      // console.log("shujuku")
      // let musicId = this.data.musicId/1
      let {shoucang , mvDetail} = this.data
      let inserlist = {
        id:mvDetail.id/1,
        name:mvDetail.name,
        url:mvDetail.cover,
        ar:mvDetail.artists,
        playCount:mvDetail.playCount
      }
      let that = this
      // console.log("11111")
      if(!shoucang){
       //  console.log("userid:",appInstance.globalData.userId)
        collectDB.where({userId:appInstance.globalData.userId}).get({
         success(res){
           // console.log("查询成功：",res)
           if(res.data.length === 0){  
             // console.log(res.data.length)
             console.log("用户不存在")
           }else{
             // console.log(appInstance.globalData.userId)
             console.log("用户存在")
             // console.log(_)
             // console.log(collectDB.doc(appInstance.globalData.userId))
             collectDB.where({userId:appInstance.globalData.userId}).update({
               data:{
                 likemvs: _.unshift(inserlist)
               },
               success: function(res) {
                 // console.log(inserlist)
                 if(res.stats.updated===1){
                   console.log("添加成功：",res)
                   that.setData({
                     shoucang:true
                   })
                 }
               },
               false(err){
                 console.log("添加失败",err)
               }
             })
             
           }
          
         }
       })
      }else{
          console.log("取消收藏")
          collectDB.where({userId:appInstance.globalData.userId}).get({
            success(res){
              // console.log("查询成功：",res)
              if(res.data.length === 0){  
                // console.log(res.data.length)
                console.log("用户不存在")
              }else{
                // console.log(appInstance.globalData.userId)
                console.log("用户存在")
                // console.log(_)
                // console.log(collectDB.doc(appInstance.globalData.userId))
                collectDB.where({userId:appInstance.globalData.userId}).update({
                  data:{
                    likemvs: _.pull(inserlist)
                  },
                  success: function(res) {
                    // console.log(inserlist)
                    if(res.stats.updated===1){
                      console.log("添加成功：",res)
                      that.setData({
                        shoucang:false
                      })
                    }
                  },
                  false(err){
                    console.log("添加失败",err)
                  }
                })
                
              }
             
            }
          })
      }
    },



    

    DBstatus(mvid){
      console.log("shujuku")
       mvid = mvid/1
      // console.log(typeof mvid)
      let that = this
      const _ = DB.command
      // console.log(_)
        collectDB.where(_.and([
          {
            userId: appInstance.globalData.userId
          },
          {
            likemvs: {
              id: mvid
            }
          }
        ]))
        .get({
          success: function(res) {
            console.log(res.data.length)
            if(res.data.length !== 0 ){
              console.log(res.data)
              that.setData({
                shoucang:true
              })
            }else{
              that.setData({
                shoucang:false
              })          
            }
          }
        })
    },

    //获取音乐url
    async getmvUrl(id){
     let res = await request('/mv/url',{id})
     let mvurl = res.data.url
    //  console.log(res)
     this.setData({
       mvurl
     })
      //  获取音乐作者
      this.getmvdetail(id)
      this.getsimimv(id)
      this.DBstatus(id)
    },
    // 获取相似MV
    async getsimimv(mvid){
      let res = await request('/simi/mv',{mvid})
      let simiMvs = res.mvs
      simiMvs.forEach((item,index)=>{
        if(item.playCount>10000){
          item.playCount = Math.round(item.playCount/10000) + '万'
        }
      })
      this.setData({
        simiMvs
      })
    },
    //获取音乐作者
    async getmvdetail(mvid){
       let res = await request('/mv/detail',{mvid})
      //  console.log(res)    
       this.setData({
         mvDetail:res.data,
         duration:res.data.duration/1000
       })
       //获取mv信息
       this.getmvinfo(mvid)
    },
       //获取mv信息
    async getmvinfo(mvid){
      
      let {mvInfo} =this.data
      let res = await request('/mv/detail/info',{mvid})
      // console.log(res)
      // console.log(res)
      mvInfo=res    
      this.setData({
        mvInfo,
        // liked:mvInfo.liked
      })
      // console.log(this.data.mvInfo)
      // 获取mv评论
      this.getmvComment(mvid) 
    },

    //添加弹幕
    async getmvComment(id){
      let {danmuList,duration,mvComment} = this.data
    //  let res = await request('/comment/mv',{id,limit:200})
    let pageNo = mvComment.length/200 +1
    // console.log(pageNo)
    let res = await request("/comment/new",{type:1,id,sortType:2,pageSize:200,pageNo})
    // console.log(res)
    //  console.log(res.data.comments)
     res.data.comments.forEach((item,index) => {
      //  console.log(Math.round(Math.random()*duration))
       let danmuItem = {}
       danmuItem = {
        text:item.content,
        color:'#cccccc',
        time:Math.round(Math.random()*duration)
       }
       danmuList.push(danmuItem)

     }); 
     mvComment.push(...res.data.comments)
     this.setData({
      danmuList,
      mvComment
     })    
    },
    chudi(){
      console.log("触底")
      let {mvid} =this.data
      this.getmvComment(mvid) 

    },

      // 点击切换到mv评论
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id-1)*60,
      
    })
  },
  // swiper发生变化
  swiperchange(event){
    // let {TabCur} = this.data
    this.setData({
      TabCur:event.detail.current
    })
  },
  //前往mv播放界面
  tomvplay(event){
    console.log(event)
    let vid = event.currentTarget.dataset.vid
    wx.navigateTo({
       url: '/pages/songPackage/pages/mvplay/mvplay?vid='+vid
     })
  },
  
  //下载mv
  xiazai(){
    console.log("xiazai")
    wx.showLoading({
      title: '缓存中',
      duration:2000
  })
          //保存视频
      //保存视频
      const  downloadTask =  wx.downloadFile({
            url:this.data.mvurl, 
            success: 
           function(res){
           console.log(res);
           var rr=res.tempFilePath;
           console.log(rr)
            wx.saveVideoToPhotosAlbum({
            filePath:`${rr}`,
            success(res) {
                wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration:  2000
                })
            }
            })
            }  
            })
          
          downloadTask.onProgressUpdate((res) => {
            console.log('下载进度', res.progress)
            console.log('已经下载的数据长度', res.totalBytesWritten)
            console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
            if(res.totalBytesWritten==res.totalBytesExpectedToWrite){
              console.log("下载完成")
              downloadTask.abort() // 取消下载任务
            }
          })
          
          
 
      
  },
  //点赞
  async dianzan(){
    let {mvid,mvInfo} = this.data
    let liked = mvInfo.liked
    let t = ''
    if(this.data.t){
      t = (this.data.t==1)?2:1
    }else{
       t = liked?2:1
    }
    
    console.log(t)
    let res = await request("/resource/like",{type:1,id:mvid,t})
    
    console.log(res)
    if(res.code=200){
      mvInfo.liked=(t==1)?true:false
      this.setData({
        mvInfo,
        t
      })
    }else if(res.code==301){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        success: () => {
          // 跳转至登录界面
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      })
    }
    console.log(t)
    console.log(this.data.mvInfo.liked)
    
  },

  async dianzan2(event){
    let dataset = event.currentTarget.dataset
    let {mvComment} = this.data
    let liked = mvComment.liked
    let t = ''
    if(mvComment[dataset.cindex].t){
      t = (mvComment[dataset.cindex].t==1)?0:1
    }else{
       t = mvComment[dataset.cindex].liked?0:1
    }
    
    console.log(t)
    let res = await request("/comment/like",{id:this.data.mvid,type:1,cid:dataset.cid,t})
    
    console.log(res.code)
    if(res.code=200){
      if(t==1){
        mvComment[dataset.cindex].likedCount++
      }else{
        mvComment[dataset.cindex].likedCount--
      }
      mvComment[dataset.cindex].liked=(t==1)?true:false
      mvComment[dataset.cindex].t = t
      this.setData({
        mvComment
      })
    }else if(res.code==301){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        success: () => {
          // 跳转至登录界面
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      })
    }

  },





    bindInputBlur(e) {
        this.setData({
          inputValue:e.detail.value
        })
      },

    bindButtonTap() {
        const that = this
        wx.chooseVideo({
          sourceType: ['album', 'camera'],
          maxDuration: 60,
          camera: ['front', 'back'],
          success(res) {
            that.setData({
              src: res.tempFilePath
            })
          }
        })
      },
     async bindSendDanmu() {
      let {enableDanmu} = this.data
      if(enableDanmu){
        if(!this.data.inputValue){
          enableDanmu = false
          this.setData({
            enableDanmu
          })
        }else{
          this.videoContext.sendDanmu({
            text: this.data.inputValue,
            color: this.getRandomColor()     
          })

          // 添加评论区
          let res = await request("/comment",{t:1,type:1,id:this.data.mvid,content:this.data.inputValue})
          // console.log(res)
          if(res.code === 200){
            let icomment = this.data.mvComment[0]
            icomment.content=res.comment.content
            icomment.liked = false
            icomment.likedCount = 0
            icomment.commentId = res.comment.commentId
            icomment.timeStr = this.turnTime(res.comment.time)
            icomment.user = res.comment.user
            // console.log(icomment)
            let {mvComment} = this.data
            // mvComment.unshift(icomment)
            // console.log(mvComment)
            this.setData({
              mvComment
            })

          }else{
            console.log("出错了")
          }

          this.setData({
            inputValue:''
          })
        }

      }else{
        enableDanmu = true
        this.setData({
          enableDanmu
        })
      }
      wx.removeStorageSync('c')
      wx.setStorageSync('enableDanmu', enableDanmu)
      },

    //时间转换
    turnTime(cTime){
              //将时间戳转换成时间格式
        // d.cTime = 1539083829787
        let date = new Date(cTime);
        let year = date.getFullYear();
        let month = date.getMonth()+1;
        let day = date.getDate();
        month = month < 10 ? "0"+month:month;
        day = day < 10 ? "0"+day:day;
        let dateturn = year+'-'+month+'-'+day;
        console.log(dateturn); // 2018-10-09
        return dateturn
    },


    getRandomColor(){
        const rgb = []
        for (let i = 0; i < 3; ++i) {
          let color = Math.floor(Math.random() * 256).toString(16)
          color = color.length == 1 ? '0' + color : color
          rgb.push(color)
        }
        return '#' + rgb.join('')
      },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function (res) {
        this.videoContext = wx.createVideoContext('myVideo')
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function ({from}) {
      console.log(from)
      if(from==='menu'){
        console.log("1111")
        return{
          title:this.data.mvDetail.name,
          page:'/pages/songPackage/pages/mvplay/mvplay',
          imageUrl:'/static/images/gocar.jpeg'
        }
      }else{
        return{
          title:this.data.mvDetail.name,
          page:'/pages/songPackage/pages/mvplay/mvplay',
          // imageUrl:'/static/images/gocar.jpeg'
          imageUrl:this.data.mvDetail.cover
        }
      }
      // console.log(from)

    }
})